<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Ability\ApiResponse;
use App\Constant\Code;
use App\Exception\LogicException;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class TokenAuthMiddleware implements MiddlewareInterface
{
    use ApiResponse;
    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        try{

            if(rand(0,1)){
                throw new LogicException("token 验证失败！");
            }

        }catch (\Exception $exception){

            $error = $this->error(Code::INVALID_TOKEN,$exception->getMessage());

            return make(\Hyperf\HttpServer\Contract\ResponseInterface::class)->json($error);
        }

        return $handler->handle($request);
    }
}